<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\controller\Redis;
use fast\Http;
use think\Db;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    private static $APPID = 'wxe106dceb5c64084a';
    private static $APPSECRET = '0ba74311a403430b8390d9b70ef5cff3';


    //审核开关
    public function check()
    {
        $this->success('','',0);//水电费乐山
    }
    //审核时需要显示的文章
    public function checks()
    {
        $data = Db::name('abc')->select()->toArray();
        foreach ($data as $k=>$v){
            $data[$k]['content'] = str_replace('"/uploads', '"http://' . $_SERVER['HTTP_HOST'].'/uploads', $data[$k]['content']);
            if(  $k == '0'){
                $data[$k]['image'] = 'https://video.zhoujiasong.top/uploads/static/1.jpg';
            }
            if(  $k == '1'){
                $data[$k]['image'] = 'https://video.zhoujiasong.top/uploads/static/2.jpg';
            }
            if(  $k == '2'){
                $data[$k]['image'] = 'https://video.zhoujiasong.top/uploads/static/3.jpeg';
            }

        }
        $this->success('ok',$data);
    }

    /*
     * 点击视频 获取 对应的阅读
     * */
    public function yuedu()
    {
        $vid = $this->request->param('vid');
        if (!$vid)$this->error('缺少参数');
        $data = Db::name('article')->where('avideo_id',$vid)->order('id desc')->find();
        if(!$data){
            $this->error('无阅读');
        }
        $data['content'] = str_replace('"/uploads', '"http://' . $_SERVER['HTTP_HOST'].'/uploads', $data['content']);
        $data['text_content']=preg_replace('~<[img|IMG](.*?)(.*?)>~s','',$data['content']);
        $this->success('成功',$data);
    }
    /*
     * 点击视频 获取 对应的阅读
     * */
    public function contenttitile()
    {
        $this->success('成功','欢迎来到民航安培');
    }
    /*
     * 点击视频 获取 对应的文字
     * */
    public function wenzi()
    {
        $vid = $this->request->param('vid');
        if (!$vid)$this->error('缺少参数');
        $data = Db::name('article_word')->where('avideo_id',$vid)->order('id desc')->find();
        if(!$data){
            $this->error('无阅读');
        }
        $this->success('成功',$data);
    }

    /**
     * 首页
     *
     */
    public function index()
    {
        $str = '[{"id":3,"arr":["A","B"],"isDuiOrCuo":false},{"id":4,"arr":["C","D"],"isDuiOrCuo":false}]';
        $ar = json_decode($str,1);
        var_dump($ar);exit;
        $this->success('请求成功',$ar);
    }
    /**
     * 联系我们
     *
     */
    public function contactus()
    {
        $company=Db::name('company')->find();
        $company['qrcodeimage']=IMG.$company['qrcodeimage'];
        $this->success('联系我们',$company);
    }
    /*
     * 学习地图 ->
     * */
    public function maps()
    {
        $period = Db::name('period')->select();
        $this->success('成功',$period);
    }
    /*
     * 微信授权
     * */
    public function wxlogin()
    {
        $code = $this->request->param("code");
        $avatarUrl = $this->request->param("avatar")??'1';
        $nickName = $this->request->param("name")??'1';
        if (!$code || !$avatarUrl || !$nickName){
            $this->error('缺少参数');
        }
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . self::$APPID . '&secret=' . self::$APPSECRET . '&js_code=' . $code . '&grant_type=authorization_code';
        $arr = Http::get($url);
        //获取openid
        $arr = json_decode($arr, true);

        //获取当前的openid
        $openId = $arr['openid'];
        //进行查询
        $personnel_find = Db::name('auser')->where("openid", $openId)->find();
        //查询是否已绑定
        $isbind = Db::name('auser')->where("openid", $openId)->where('cate_id','eq','')->find();

        if ( !empty($personnel_find) || $isbind ) {

            $payload = array('iss'=>'admin','iat'=>time(),'exp'=>time()+72000000000,'nbf'=>time(),'sub'=>'www.admin.com','uid'=>$personnel_find['id']);
            $token = Jwt::getToken($payload);
            $personnel_find['token'] = $token;
            $return = json_encode($personnel_find);
            $personnel_find['isnew'] = 0;
            $this->success('登录成功', $return);
        } else {
            //获取当前openId
            $personnel_data['openid'] = $openId;
            //获取当前昵称
            $personnel_data['name'] = $nickName;
            //获取当前头像
            $personnel_data['avatar'] = $avatarUrl;
            //获取当前时间
            $personnel_data['ctime'] = date("Y-m-d H:i:s",time());
            //执行添加操作
            $personnel_id = Db::name('auser')->insertGetId($personnel_data);
            //进行查询
            $personnel_find = Db::name('auser')->where('id', $personnel_id)->find();
            $payload = array('iss'=>'admin','iat'=>time(),'exp'=>time()+72000000000,'nbf'=>time(),'sub'=>'www.admin.com','uid'=>$personnel_find['id']);
            $token = Jwt::getToken($payload);
            $personnel_find['token'] = $token;
            $personnel_find['isnew'] = 1;
            $return = json_encode($personnel_find);
            $this->success('登录成功', $return);
        }
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 微信授权
     */
    public function wx_code()
    {
        $code = $this->request->param("code");
        if (!$code){
            $this->error('缺少参数');
        }
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . self::$APPID . '&secret=' . self::$APPSECRET . '&js_code=' . $code . '&grant_type=authorization_code';
        $arr = Http::get($url);
        //获取openid
        $arr = json_decode($arr, true);
        //获取当前的openid
        $openId = $arr['openid'];
        //进行查询
        $personnel_find = Db::name('auser')->where("openid", $openId)->find();
        //查询是否已绑定
        $isbind = Db::name('auser')->where("openid", $openId)->where('cate_id','eq','')->find();
        if ( !empty($personnel_find) || $isbind ) {

            $payload = array('iss'=>'admin','iat'=>time(),'exp'=>time()+72000000000,'nbf'=>time(),'sub'=>'www.admin.com','uid'=>$personnel_find['id']);
            $token = Jwt::getToken($payload);
            $personnelarr['token'] = $token;
            $personnelarr['isnew'] = 0;
            $return = json_encode($personnelarr);
            $this->success('登录成功', $return);
        } else {
            //获取当前openId
            $personnel_data['openid'] = $openId;
            //获取当前时间
            $personnel_data['ctime'] = date("Y-m-d H:i:s",time());
            //执行添加操作
            $personnel_id = Db::name('auser')->insertGetId($personnel_data);
            //进行查询
            $personnel_find = Db::name('auser')->where('id', $personnel_id)->find();

            $payload = array('iss'=>'admin','iat'=>time(),'exp'=>time()+72000000000,'nbf'=>time(),'sub'=>'www.admin.com','uid'=>$personnel_find['id']);
            $token = Jwt::getToken($payload);
            $personnelarr['token'] = $token;
            $personnelarr['isnew'] = 1;
            $return = json_encode($personnelarr);
            $this->success('登录成功', $return);
        }
    }
    /*
    * 获取公司
    * */
    public function allgong()
    {
        $data = Db::name('gongsi')->select();
        $this->success('成功', $data);
    }
    /*
     * 获取全部 顶级部门
     * */
    public function alldep()
    {
        $data = Db::name('category')
            ->where('pid',0)
            ->field('name,id')
            ->where('type','department')
            ->select()->toArray();
        foreach ($data as $k=>$v){
            if ($v['id'] == 49){
                unset($data[$k]);
            }
        }
        $arr = Db::name('category')->where('pid',49)->field('name,id')->select()->each(function ($item){
            $item['state'] = '体验部门';
            $item['pid'] = 49;
            return $item;
        })->toArray();
        //加入 临时游客/行业人士/管理部门 , 改为选择一级部门
        $data  = array_merge($data,$arr);
        ksort($data);
        $this->success('成功', $data);
    }
    /*
     * 获取子部门
     * */
    public function zdep()
    {
        $cid = $this->request->param('pid');//顶级部门id
        $data = Db::name('category')
            ->where('pid',$cid)
            ->field('name,id')
            ->select();
        if ($data){
            $this->success('成功', $data);
        }
        $this->error('无下级子部门');
    }
    public function catedata(){
        $data = Db::name('category')
            ->field('name,id,pid')
            ->where('type','department')
            ->select()->toArray();
        $catedata=catearr($data,0);
        $this->success('成功', $catedata);
    }
    /*
     * 获取职位
     * */
    public function allzhi()
    {
        $pid = $this->request->param('pid');
        $sons = Db::name('category')->where('pid',$pid)->field('name,id')->select();
        if ($sons){
            $this->success('成功', $sons);
        }
        $this->error('无职位');
    }

    /*
     * 组织架构图
     * */
    public function zuzhi()
    {
//        $tiyan = Db::name('category')->where('pid',49)->field('id,name')->select()->toArray();
//        foreach ($tiyan as $k=>$v){ //查找体验部门的人员
//            $tiyan[$k]['user'] = Db::name('auser')->whereIn('scate_id',$v['id'])->field('id,name,avatar,jobs')->select();
//        }

        //查找其他部门
        $cate = Db::name('category')->where('pid',0)->field('id,name')->select()->toArray();
        foreach ($cate as $k=>$v){
            if ($v['id'] == 49){
                unset($cate[$k]);
                continue;
            }
            $cate[$k]['user'] = Db::name('auser')->whereIn('cate_id',$v['id'])->field('id,name,avatar,jobs')->select();
        }
//        $arr = array_merge($tiyan,$cate);
        $this->success('成功',$cate);
    }

    /*
     * 点击查看某人的学习轨迹
     * */
    public function trail()
    {
        $uid = $this->request->param('uid');
        $userinfo = Db::name('auser')->where('id',$uid)->field('all_fen,xue_fen,longs')->find();
        $exams = Db::name('exam_record')->where('auser_id',$uid)->order('id desc')->field('ctime,usedtime,pass,point,ispass,exam_id')->select()->each(function ($v){
            $v['name'] = Db::name('exam')->where('id',$v['exam_id'])->value('name');
            return $v;
        });
        $ret['top'] = $userinfo;
        $ret['rec'] = $exams;
        $this->success('成功',$ret);
    }
    /*
     * 点击查看某个人的个人信息
     * */
    public function uinfo()
    {
        $uid = $this->request->param('uid');
        if (!$uid) $this->error('缺少参数');
//        $userinfo = Db::name('auser')->where('id',$uid)->find();
        // 姓名 头像 部门  收藏数 课程数  考试数
        $user = Db::name('auser')->where('id', $uid)->find();
        if (!$user)$this->error('查无此人信息');
        //查询此人是否为机场领导角色
        if ($user['cate_id'] == 1){
            $user['leader'] = '1';
        }else{
            $user['leader'] = '0';
        }
        $user['isleader']=Db::name('category')->where('id',$user['cate_id'])->value('isleaderswitch');
        if(empty($user['isleader'])){
            $user['isleader']='0';
        }
        $user['zans_count'] = Db::name('zans')->where('auser_id',$uid)->count()??0;
        $user['exams_count'] = Db::name('exam_record')->where('auser_id',$uid)->count()??0;
        //考试需要加上未测试的数
        $already = Db::name('exam_record')->where(['auser_id'=>$uid])->column('exam_id');
        //未测试的考试
        $avideo_ids=cate_avideo($uid);
        $undo = Db::name('exam')
            ->whereNotIn('id',$already)
            ->whereIn('avideo_id',$avideo_ids)
            ->count();
        $user['exams_count'] =  $user['exams_count'] + $undo;

        $user['colles_count'] = Db::name('colles')->where('auser_id',$uid)->count()??0;
        $redis = Redis::getInstance()->getRedisConn();
        $re = $redis->hGetAll('user_'.$uid)??[];
        $user['class_count'] = sizeof($avideo_ids);

        $jobs_id=$user['jobs_id'];
        $cates=pid_cate($jobs_id);
        $jobscate=Db::name('category')->where('id',$jobs_id)->find();

        $cid = Db::name('category')->where('id',$jobs_id)->value('switch');
        if($cid == '1'||$user['isleader']=='1'){
            $user['pid'] = 0;//说明是部门负责人 , 可查看当前部门下的所有人员信息
            $user['role'] = '1';
        }else{
            $user['role'] = '0';
        }
        $catearr=array();
        for ($i=count($cates)-1;$i>=0;$i--){
            $catearr['id']=$cates[$i];
            $cate=Db::name('category')->where('id',$cates[$i])->find();
            $catearr['name']=$cate['name'];
            if(($jobscate['leveldata']!='1')){
                if($cate['leveldata']!='1'){
                    $cats[]=$catearr;
                }
            }else{
                $cats[]=$catearr;
            }
        }
        $user['cates']=$cats;
        $this->success('成功',$user);
    }

    /*
     * 点击某个视频, 跳转所属视频合集
     * */
    public function vcollect()
    {
        $vid = $this->request->param('vid');
        $cid = Db::name('avideo')->where('id',$vid)->find();
        if (!$cid){
            $this->error('此视频不存在');
        }
        $col = Db::name('col')->find($cid['col_id']);
        if (!$col){
            $this->error('无此合集');
        }
        $count = Db::name('avideo')->where('col_id',$col['id'])->count();
        $ret['count'] = $count;//合集总数
        $ret['name'] = $col['name'];//合集名称
        $ret['videos'] = $this->getVideo($col['id']);
        $this->success('ok',$ret);
    }

    /*
     * 获取视频信息---统一封装
     * @param $cate_id int  视频分类id
     * @param $type int  视频所属类型   0=必修,1=选修,2=推荐
     * */
    private function getVideo($cate_id = '', $page= 1 ,$num= 10)
    {
        $where_cate = '';
        if ($cate_id){
            $where_cate = ['col_id'=>$cate_id];
        }
        $vmodel = new \app\admin\model\Avideo();
        $data = $vmodel::with('com,category')
            ->where($where_cate)
//            ->page($page, $num)
            ->order('weigh asc')
            ->select()->each(function ($item){
                if (sizeof($item['com']) > 0) {
                    //查询评论人信息
                    foreach ($item['com'] as $k=>$v){
                        $user = \app\admin\model\Auser::get($v['auser_id']);
                        if(empty($user)){
                            unset($item['com'][$k]);
                        }else{
                            $item['com'][$k]['name'] = $user['name'];
                            $item['com'][$k]['avatar'] = $user['avatar'];
                        }
                    }
                    $item['comments'] = sizeof($item['com']);
                }else{
                    $item['comments'] = 0;
                }

                return $item;
            });
        return $data;
    }


    /*
     * 查看排名 根据用户id 和 考试的id  查询当前用户在某个考试的排名
     * */
    public function ords($uid = 7,$exam_id=1)
    {
        $str = "SELECT R.rownum,R.auser_id FROM(
SELECT t.*, @rownum := @rownum + 1 AS rownum

FROM (SELECT @rownum := 0) as r, vd_exam_record AS t  where exam_id=$exam_id

ORDER BY t.point DESC) AS R  where R.auser_id = $uid;";
        $ret = Db::name('exam_record')->query($str);
        list($paiming)= $ret;
        return ($paiming['rownum']);
    }


    /*
     * 视频的人们搜索标签
     * 就把最新上传的视频名搜索出来就行
     * */
    public function stu()
    {
        $rr = Db::name('avideo')->order('id desc')->page('1','5')->column('name');
        $this->success('成功',$rr);
    }

    /*
     * 获取所有部门
     * */
    public function alls()
    {
        $jobs_id = $this->request->param('jobs_id');//部门id
        if(empty($jobs_id)){
            //获取所有一级部门, 除领导部门外
            $cate = Db::name('category')->where('pid','0')->where('id','neq','1')->field('id,name')->select()->toArray();
            foreach ($cate as $k=>$v){
                if ($v['id'] == 49){
                    unset($cate[$k]);
                }
            }
            $arr = [
                ['id'=> 49,'name' => '临时游客'],
                ['id'=> 49,'name' => '行业人士'],
                ['id'=> 49,'name' => '管理部门']
            ];
            //加入 临时游客/行业人士/管理部门 , 改为选择一级部门
            $cate  = array_merge($cate,$arr);
        }else{
            $jobs_id = $this->request->param('jobs_id');//部门id
//获取所有一级部门, 除领导部门外
            $zongcate = Db::name('category')->field('id,name,pid')->select()->toArray();
            $cid=gettop($zongcate,$jobs_id);
            $cate = Db::name('category')->where('pid',$cid)->field('id,name')->select()->toArray();
        }
        ksort($cate);
        $this->success('成功',$cate);
    }

    /*
     * 部门下的团队
     * */
    public function myteam()
    {
        $cid = $this->request->param('cid');//部门id
        $gettime = $this->request->param('gettime'); //请求时间
        if(empty($gettime)){
            $gettime=date('Y-m',time());
        }
        //2,查找我的部门分类下面的所有人员
        $users = Db::name('auser')->where('cate_id',$cid)->field('id,name,avatar,xue_fen,ji_fen,longs,cate_id')->select()
            ->each(function ($item) use ($gettime){
                $avideo_ids=Db::name('avideo')->where('cate_id',$item['cate_id'])->column('id');
                if(empty($gettime)){
                    $item['yingcheng']=Db::name('avideo')->where('type',0)->where('cate_id',$item['cate_id'])->count();
                    $okkecheng =Db::name('point')->where('type',1)->count();
                    $item['nocheng'] =intval($item['yingcheng'])-intval($okkecheng);
                    //考试次数 / 通过次数
                    $item['all'] = Db::name('exam')->where('avideo_id',$avideo_ids)->count();
                    $pass = Db::name('exam_record')->where('auser_id',$item['id'])->where('ispass','1')->count();
                    $item['no_pass']=intval($item['all'])-intval($pass);
                }else{
                    $time=date('Y-m',strtotime($gettime));
                    $starttime=$time.'-01 00:00:00';
                    if($time==date('Y-m',time())){
                        $wheretime['ctime']=['>', $starttime];
                    }else{
                        $endtime=date('Y-m',strtotime('+1 month',strtotime($gettime)));
                        $endtime=$endtime.'-01 00:00:00';
                        $wheretime['ctime']=['between', [$starttime,$endtime]];
                    }
                    //考试次数 / 通过次数
                    $period_id=Db::name('period')->where('name',$gettime)->value('id');
                    $all_exam_ids= Db::name('exam')->where('cate_id',$item['cate_id'])->where('period_id',$period_id)->column('id');
                    $all_avideo_ids= Db::name('avideo')->where('cate_id',$item['cate_id'])->where('period_id',$period_id)->column('id');

                    $ji_fen1 =Db::name('point')->where('type',0)->where('auser_id',$item['id'])->whereIn('avideo_id',$all_avideo_ids)->sum('jifen');
                    $ji_fen2=Db::name('point')->where('type',0)->where('auser_id',$item['id'])->whereIn('exam_id',$all_exam_ids)->sum('jifen');
                    $item['ji_fen']=$ji_fen1+$ji_fen2;

                    $xue_fen1 =Db::name('point')->where('type',1)->where('auser_id',$item['id'])->whereIn('avideo_id',$all_avideo_ids)->sum('xuefen');
                    $xue_fen2 =Db::name('point')->where('type',1)->where('auser_id',$item['id'])->whereIn('exam_id',$all_exam_ids)->sum('xuefen');
                    $item['xue_fen']=$xue_fen1+$xue_fen2;

//                    学习任务
                    $item['yingcheng']=Db::name('avideo')->where('type',0)->where('cate_id',$item['cate_id'])->where('period_id',$period_id)->count();
                    $okkecheng =Db::name('point')->where('type',1)->where('auser_id',$item['id'])->whereIn('avideo_id',$all_avideo_ids)->count();
                    $item['nocheng'] =intval($item['yingcheng'])-intval($okkecheng);

//                    考试
                    $item['all'] = Db::name('exam')->where('cate_id',$item['cate_id'])->where('period_id',$period_id)->count();
                    $pass = Db::name('exam_record')->where('auser_id',$item['id'])->where('ispass','1')->whereIn('id',$all_exam_ids)->count();
                    $item['no_pass']=intval($item['all'])-intval($pass);
                }
                return $item;
            });
        if(strtotime($gettime.'-01 00:00:00')>mktime(0,0,0,date('m'),1,date('Y'))){
            $users=[];
        }
        $data['users'] = $users;
        $data['catename'] = Db::name('category')->where('id',$cid)->value('name');
        $data['count'] = (string)count($users);
        $weiwancheng=0;
        $weitongguo=0;
        foreach ($users as $k=>$v){
            if($users[$k]['nocheng']!=0){
                $weiwancheng++;
            }
            if($users[$k]['no_pass']!=0){
                $weitongguo++;
            }
        }
        $data['weiwancheng'] =(string)$weiwancheng;
        $data['weitongguo'] = (string)$weitongguo;
        $data['date'] = date('Y-m');
        $this->success('成功',$data);
    }
    /**
     *学分说明
     */
    public function xuefenintro(){
        $xuefenintro=Db::name('xuefenintro')->find();
        $this->success('学分说明',$xuefenintro['intro']);
    }
    /**
     *积分说明
     */
    public function jifenintro(){
        $jifenintro=Db::name('jifenintro')->find();
        $this->success('积分说明',$jifenintro['intro']);
    }
}
